
--字符串分割函数
--传入字符串和分隔符，返回分割后的table
local function split(str, delimiter)
	if str==nil or str=='' or delimiter==nil then
		return nil
	end
    local result = {}
    for match in (str..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match)
    end
    return result
end
local ltrim = function (content)
	local rsl,_ = string.gsub(content, "^%s*(.*)$", "%1")
	return rsl
end
local rtrim = function (content)
	return string.reverse(ltrim(string.reverse(content)))
end
local trim = function (content)
	return rtrim(ltrim(content))
end
--获取cookie
local getCookie = function (req)
    local cookies = {}
    local cookieStr = req.headers.Cookie
    local group = split(cookieStr, ";")
    if group then
        for index, item in ipairs(group) do
            local keyVal = split(item, "=")
            if keyVal then
                local key = trim(keyVal[1])
                local val = trim(keyVal[2])
                if key then
                    cookies[key] = val
                end
            end
        end
    end
    return cookies
end

--绑定设置cookie的方法
local bindSetCookie = function (resp)
    function resp:setCookie(key, val, opt)
        local header = tostring(key) .. "=" .. tostring(val)
        if opt and opt.Expires then
            header = header .. "; Expires=" .. tostring(opt.Expires)
        end
        if opt and opt.Domain then
            header = header .. "; Domain=" .. tostring(opt.Domain)
        end
        if opt and opt.Path then
            header = header .. "; Path=" .. tostring(opt.Path)
        end
        local cookies = resp:getHeader("Set-Cookie")
        if "string" == type(cookies) then
            resp:setHeader("Set-Cookie", {cookies, header})
        elseif "table" == type(cookies) then
            table.insert(cookies, header)
            resp:setHeader("Set-Cookie", cookies)
        else
            resp:setHeader("Set-Cookie", header)
        end
    end
end

local M = {}
M.getCookie = getCookie
M.bindSetCookie = bindSetCookie

local moduleName = ...
_G[moduleName] = M
complex = M
return complex